package servlet;

import DBCon.DBCon;
import model.User;
import service.UserService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Register_Servlet extends HttpServlet {
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        System.out.println("注册页面");
        HttpSession session = req.getSession();
        String name = req.getParameter("u_name");
        String pwd = req.getParameter("u_password");
        String  Email= req.getParameter("Email");
        String real_name = req.getParameter("real_name");
        String tel = req.getParameter("tel");
        String sex = req.getParameter("sex");
        String date_birth = req.getParameter("date_birth");
        User user = new User(name, pwd, Email, real_name, tel, sex, date_birth);
        UserService userService = new UserService();
        String msg = userService.register(user);
//        String str_msg = "<script>alert('" + msg + "')</script>";
//        req.setAttribute("msg", str_msg);
//        if (msg.equals("注册成功！")) {
//            PrintWriter out = resp.getWriter();
//            out.print("<script>alert('注册成功！')</script>");
//            out.print("<script>window.location.href='login.jsp'</script>");
//        } else {
//            req.getRequestDispatcher("register.jsp").forward(req, resp);
//        }
        if (msg.equals("注册成功！")) {
            session.setAttribute("msg",msg);
            resp.sendRedirect("login.jsp");
        } else {
            System.out.println("123");
            session.setAttribute("fail",false);
            resp.sendRedirect("register/register.jsp");
        }
    }
}
